package com.imooc.SmartChargeStation.netty.server.utils;

import com.alibaba.fastjson2.JSON;
import com.zhangyt.mqtt.message.ChargePayload;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;

/**
 * author: Imooc
 * description: OKHTTP工具类
 * date: 2025
 */

@Slf4j
public class HTTPUtils {

    /**
     * author: Imooc
     * description: post请求
     * @param body:  私有协议的实体类
     * @return void
     */
    public static void doPOST(ChargePayload body) {

       //把Java对象转换为Json对象
       String json = JSON.toJSONString(body);

       OkHttpClient client =   new OkHttpClient();

       //把媒体类型设为application/json
       MediaType mediaType = MediaType.get("application/json; charset=utf-8");
       RequestBody reqBody =  RequestBody.create(json, mediaType);

       Request request = new Request.Builder()
                        //注意host文件的配置,否则不认识mqtt域名
                           .url("http://123.60.95.133:8033/mqtt/send")
                        //注意要Java对象转换为Json对象
                        .post(reqBody)
                        .build();

       //请求成功还是失败
       isOk(client, request);


    }

    /**
     * author: Imooc
     * description: 请求是否成功
     * @param client: OKHTTP客户端对象
     * @param request:  请求对象
     * @return void
     */
    private static void isOk(
            OkHttpClient client,
            Request request) {

        try {
           Response response = client.newCall(request).execute();
           if(response.isSuccessful()) {
               String res = response.body().string();
               log.info("mqtt发送Api返回信息："+res);
           }
        } catch (IOException e) {
            log.error("mqtt发送Api调用失败");
            e.printStackTrace();
        }

    }

}
